const getDonor = document.querySelector('.getDonor')
const getUnit = document.querySelector('.getUnit')
const getMoney = document.querySelector('.getMoney')
const getDate = document.querySelector('.getDate')

const add = document.querySelector('.add')
let data = []
data = JSON.parse(localStorage.getItem('donorlistData'))
add.addEventListener('click', function () {
    tbody.innerHTML = ''
    let getdata = {
        person: getDonor.value,
        unit: getUnit.value,
        money: getMoney.value,
        date: getDate.value,
    }
    data.push(getdata)
    localStorage.setItem('donorlistData',JSON.stringify(data))
    colours()
})

const tbody = document.querySelector('tbody')
function colours(array = data) {
    tbody.innerHTML = ''
    for (let i = 0; i < array.length; i++) {
        const iten = array[i]
        let trs = document.createElement('tr')
        trs.innerHTML = `
            <td>${i}</td>
            <td>${iten.person}</td>
            <td>${iten.unit}</td>
            <td>${iten.money}</td>
            <td>${iten.date}</td>
            <td>
              <a href="#" class="del" data-id=${i}>删</a>
              <a href="#" class="update">改</a>
            </td>
    `
        tbody.appendChild(trs)
    }
}
colours()

tbody.addEventListener('click',function(e){
    if (e.target.classList.contains('del')) {
        let index = e.target.dataset.id
        data.splice(index,1)
        localStorage.setItem('donorlistData',JSON.stringify(data))
        tbody.innerHTML = ''
        colours()
    }
})

const search = document.querySelector('.search')
const searchValue = document.querySelector('.searchValue')
search.addEventListener('click',function(){
    let vl = searchValue.value
    for (let  i = 0;  i < data.length;  i++) {
        console.log(data[i]);
        let obj = data[i].unit
        if (vl!==obj) {
            data[i].splice(i,1)
        }
    }
    const unit = searchValue.value;
    if(unit === "") {
        colours();
        return;
    }
    const result = [];
    for (let index = 0; index < data.length; index++) {
        const item = data[index];
        if(item.unit === unit) {
            result.push(item)
        }
    }
    colours(result)
})
